<?php
// +----------------------------------------------------------------------
// | [ WE ONLY DO WHAT IS NECESSARY ]
// +----------------------------------------------------------------------
// | Author < 931274989@qq.com >
// +----------------------------------------------------------------------
// | Explain 玻璃水
// +----------------------------------------------------------------------
namespace app\ymkj\controller;

use app\model\Bolishui as bolishuiModel;
use app\model\Order as orderModel;
use think\facade\Session;
use think\Controller;
use think\Db;
 
class Bolishui extends Controller
{
  public function index()
  {
    $data = request()->param();
    $user = Session::get('wewhat_user');
    $pinshui = Db::name('user')->where('openid','=',$user['openid'])->value('bolishui');
    $qiname = Db::name('xiche')->where('id','=',$data['xid'])->value('name');
    $this->assign([
      'pinshui' => $pinshui,
      'xid' => $data['xid'],
      'qiname' => $qiname,
    ]);
    return view();
  }

  public function order(){
    $data = request()->param();
    $model = new bolishuiModel();
    $user = Session::get('wewhat_user');
    $pinshui = Db::name('user')->where('openid','=',$user['openid'])->value('bolishui');
    if($pinshui < $data['pinshu']){
      return $this->error('玻璃水不足');
    };
    $data['openid'] = $user['openid'];
    Db::startTrans();
    $result = $model->save($data);
    $boli = Db::name('user')->where('openid','=',$user['openid'])->setDec('bolishui',(int)$data['pinshu']);
    Db::commit();
    if($result && $boli) {
      $jine = $data['pinshu'] * 100;
      $order = new orderModel();
      $createOrder = $order->save([
        'shop_id' => $data['xid'],
        'openid' => $user['openid'],
        'name' => "加玻璃水",
        'jine' => $jine,
        'bid' => $model->id
      ]);
      if( $createOrder ){
        return redirect('Buy/index',array('order_id'=>$order->id));
        //return redirect('Wechat1/save')->with(['name'=>"加玻璃水",'order_id'=>$order->id,'price'=>$jine,'openid'=>$user['openid']]);
      } else {
        $this->error('下单失败');
      }
    } else {
      Db::rollback();
      $this->error('玻璃水添加失败');
    }
  }
}
?>